<template>
  <el-container style="margin: 0;padding: 0;height: 100%">
    <el-drawer
        title="气象站点信息"
        :visible.sync="markershow"
        direction="ltr"
        size="30%"
        :with-header=false
    >
      <el-container style="padding-top: 20px">
        <el-header>
          <el-icon class="el-icon-alarm-clock" style="color: #409EFF"></el-icon>
          <span style="font-size: 16px;font-weight: 600;color: #409EFF">   {{ markerform.factor.createTime }}</span>
          <span style="font-size: 16px;font-weight: 600;margin-left: 20px">  气象站点详情</span>
        </el-header>
        <el-main>
          <el-col>
            <el-form :model="markerform" label-position="left" label-width="140px">
              <el-form-item label="站点名称">
                <el-input v-model="markerform.stationName" readonly>
                  <el-button slot="append" icon="el-icon-s-promotion"
                             style="background-color: rgba(64,158,255,0.3)"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="站点级别">
                <el-radio-group v-model="markerform.stationLevel">
                  <el-radio :label="1">国家级气象站点</el-radio>
                  <el-radio :label="2">地方气象站点</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="地理位置">
                <el-input v-model='location' readonly>
                  <el-button slot="append" icon="el-icon-location"
                             style="background-color: rgba(64,158,255,0.3)"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="6分钟平均气温">
                <el-input v-model='temperature' readonly>
                  <el-button slot="append" icon="el-icon-odometer"
                             style="background-color: rgba(64,158,255,0.3)"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="6分钟平均降水">
                <el-input v-model='this.V50029' readonly>
                  <el-button slot="append" icon="el-icon-light-rain"
                             style="background-color: rgba(64,158,255,0.3)"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="6分钟平均气压">
                <el-input v-model='this.PRS' readonly>
                  <el-button slot="append" icon="el-icon-loading"
                             style="background-color: rgba(64,158,255,0.3)"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="6分钟相对湿度">
                <el-input v-model='this.RHU' readonly>
                  <el-button slot="append" icon="el-icon-data-analysis"
                             style="background-color: rgba(64,158,255,0.3)"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="平均2分钟风向">
                <el-input v-model='this.markerform.factor.win_D_Avg_2mi' readonly>
                  <el-button slot="append" icon="el-icon-wind-power"
                             style="background-color: rgba(64,158,255,0.3);"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="平均2分钟平均风速">
                <el-input v-model='this.WIN_S_Avg_2mi' readonly>
                  <el-button slot="append" icon="el-icon-timer"
                             style="background-color: rgba(64,158,255,0.3);"></el-button>
                </el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-main>
        <el-footer>
          <el-button type="primary" style="width: 100%" @click="markershow=false">关闭</el-button>
        </el-footer>
      </el-container>
    </el-drawer>
    <el-main style="padding: 0px;margin: 0px">
      <div class="main_map" id="map"></div>
      <div
          style="position: absolute; bottom: 30px;left:250px; z-index: 999; display: flex; justify-content: center;align-items: center">
        <el-button-group style="padding-left: 20px;text-align: center;display: flex;align-items: center">
          <el-button style="font-weight: bold;font-size: 13px;margin-right: 13px">
            {{ formatTime(this.currentTimeStamp) }}
          </el-button>

          <!--        自动轮播的时候自动更改样式-->
          <el-button class="window" v-for="(image,index) in nameList"
                     :class="{ activeButton: currentImageIndex === index }"
                     style="width: 5px;margin-right: 10px;padding-left: 10px;padding-right: 10px"
                     @click="showImageLayer(image,index)"></el-button>
        </el-button-group>
        <el-button @click="togglePlay" style="padding: 5px">
          <el-icon :class="isPlaying?'el-icon-video-pause':'el-icon-video-play'" style="font-size: 20px"></el-icon>
        </el-button>
      </div>

    </el-main>
  </el-container>
</template>

<script>
import L from "leaflet"
import moment from "moment";
import "leaflet/dist/leaflet.css"
import {getLatestStationInfo} from "@/api/java/stationInfo";
import {getLatestLogAndNameList} from "@/api/java/radarLog";

export default {
  name: "leafletMap",
  mounted() {
    this.getLogAndNameList()
  },
  beforeMount() {
    // 初始化连接WebSocket 接收每次新的雷达基文件到达的名称
    const socket = new WebSocket("ws://localhost:8089/websocket");
    socket.onopen = () => {
      console.log("连接成功")
    }
    socket.onmessage = (event) => {
      this.$message.info("新的雷达基数据到来")
      getLatestLogAndNameList().then(res => {
        this.$store.dispatch("SETCURRENTTIMESTAMP", res.data.currentName)
        this.$store.dispatch("SETPREDICTIONLIST", res.data.nameList)
        this.currentTimeStamp = res.data.currentName
        this.nameList = res.data.nameList
        // 监听到新数据之后切换图层
        this.radarEchoImageLayer.clearLayers()
        this.rawRadarImageLayer = this.radarImagePrefix + this.currentTimeStamp + ".png"
        this.radarEchoImageLayer.addLayer(L.imageOverlay(this.rawRadarImageLayer, this.imageBounds, {opacity: 0.8}))
        // 切换降雨图层
        this.rainImageLayerGroup.clearLayers()
        var rainImageLayer = this.rainImagePrefix + this.currentTimeStamp + ".png"
        this.rainImageLayerGroup.addLayer(L.imageOverlay(rainImageLayer, this.imageBounds, {opacity: 0.8}))
        this.currentImageIndex = 0
      })
    }
  },
  computed: {
    // 站点地理位置
    location() {
      return this.markerform.latitude + "°N," + this.markerform.longitude + "°E"
    },
    // 记录站点六分钟平均气温
    temperature() {
      return this.markerform.factor.tem + " ℃"
    },
    // 记录站点六分钟平均降水
    V50029() {
      return this.markerform.factor.v50029 + " mm/min"
    },
    // 记录站点六分钟平均气压
    PRS() {
      return this.markerform.factor.prs + " hpa"
    },
    // 站点六分钟平均相对湿度
    RHU() {
      return this.markerform.factor.rhu + " %"
    },
    // 平均两分钟平均风速
    WIN_S_Avg_2mi() {
      return this.markerform.factor.win_S_Avg_2mi + " m/s"
    },
    currentTime() {
      if (this.currentImageIndex === -1) {
        var year = this.currentTimeStamp.substring(0, 4)
        var month = this.currentTimeStamp.substring(4, 6)
        var day = this.currentTimeStamp.substring(6, 8)
        var hour = this.currentTimeStamp.substring(8, 10)
        var minute = this.currentTimeStamp.substring(10, 12)
        return year + "/" + month + "/" + day + " " + hour + ":" + minute + "00"
      }
    }
  },
  created() {

    // 初始化气象站marker的图标信息
    this.markerIcon = L.icon({
      iconUrl: require('@/assets/marker-icon-2x.png'),
      iconSize: [25, 41],
      iconAnchor: [12, 41],  //相对于坐标的偏移位置
    });
    // 初始化雷达站点Icon
    this.radarIcon = L.icon({
      iconUrl: require('@/assets/radarIcon.svg'),
      iconSize: [50, 100],
      iconAnchor: [12, 41]
    })
    // 设置定时器 定时拉取气象站信息,拉取间隔时间为1分钟
    this.StationInfointerVal = setInterval(() => {
      // this.GetStationInterval()
    }, 1000 * 60)
  },
  data() {
    return {
      map: null,
      currentTimeStamp: null,
      markerIcon: null,
      nameList: [],
      marker: null,
      StationInfointerVal: null,  //定时器  定时拉取气象站信息
      markershow: false,
      // 点击国家自动气象站绑定到表单上面进行回显
      markerform: {
        stationName: '',
        stationCode: '',
        latitude: '',
        longitude: '',
        stationLevel: null,
        factor: {},
      },
      activeIndex: "1",
      stamenLayer: null,  //地理底层图层
      radarMarker: null,  //雷达站点
      radarStationLayer: null,  //雷达站点图层
      radarStation: [114.71194444, 38.35194444],  //雷达站经纬度信息
      baseMap: null,  //基础地图图层
      overlayMap: null,  //气象站点图层
      radarEchoImageLayer: null,//雷达回波外推图层控制组
      rawRadarImageLayer: null,//默认情况下显示的当前雷达外推图层
      rainImageLayerGroup: null,//降雨图层控制组
      center: [38.042007, 114.514976],//图层显示的核心位置
      layerBounds: [[37.50318937824072, 113.20999145507814], [38.81617117607388, 115.66268920898439]],//显示的边界值
      imageBounds: [[37.0, 113.5], [39.0, 115.5]], //控制雷达回波图边界值显示
      currentImageIndex: -1,
      isPlaying: false,
      intervalId: null,
      radarImagePrefix: this.$config.radarImage,  //存放雷达外推结果的前缀
      rainImagePrefix: this.$config.rainImage,//降雨图前缀
      mapImagePrefix: this.$config.mapPath,//地图图片前缀

    }
  },
  methods: {
    // 定时轮播
    // 播放或暂停轮播
    togglePlay() {
      if (this.isPlaying) {
        // 如果正在播放，点击后暂停轮播
        this.stopAutoPlay();
      } else {
        // 开始播放
        this.startAutoPlay();
      }
    },
    // 开始自动轮播
    startAutoPlay() {
      this.isPlaying = true;
      this.intervalId = setInterval(() => {
        // 切换到下一张图片
        this.currentImageIndex = (this.currentImageIndex + 1) % this.nameList.length;
        this.showImageLayer(this.nameList[this.currentImageIndex], this.currentImageIndex);
      }, 1000); // 每1秒切换一张图片，调整为你需要的速度
    },

    // 停止自动轮播
    stopAutoPlay() {
      this.isPlaying = false;
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
    },
    // 定时拉取气象站信息任务  保存到vuex
    GetStationInterval() {
      this.$message.info('定时拉取气象站点信息')
      this.$store.dispatch('GetStation')
      this.stationLayers.clearLayers()
      // 同时更新气象站对应层
      this.$store.state.stationInfo.forEach(item => {
        var marker = L.marker([item.latitude, item.longitude], {
          icon: this.markerIcon,
          opacity: 0.9
        }).addTo(this.stationLayers)
        // 绑定自动气象站点击事件,弹出嵌套框显示实时气象要素信息
        marker.on('click', () => {
          this.markerform = item
          this.markershow = true
          this.map.flyTo([item.latitude, item.longitude])
          this.map.setView([item.latitude, item.longitude], 11)
        })
      })
    },
    // 初始化拉取默认时间戳和未来预测名称
    getLogAndNameList() {
      getLatestLogAndNameList().then(res => {
        this.$store.dispatch("SETCURRENTTIMESTAMP", res.data.currentName)
        this.$store.dispatch("SETPREDICTIONLIST", res.data.nameList)
        this.currentTimeStamp = res.data.currentName
        this.nameList = res.data.nameList
        this.initMap()
      })
    }
    ,
    initMap() {
      // 声明地理信息图层
      this.stamenLayer = L.tileLayer(this.mapImagePrefix + '{z}/{x}/{y}/tile.png', {  //设置瓦片地图图层
        minZoom: 10,
        maxZoom: 17,
        attribution: '© Nuist GIS & 石家庄气象局', //图层注释
      })


      // 声明气象站点图层
      this.stationLayers = L.layerGroup()
      getLatestStationInfo().then(res => {
        // 首次加载站点的同时存储到vuex中
        res.data.forEach(item => {
          // 气象站点添加到图层中
          var marker = L.marker([item.latitude, item.longitude], {
            icon: this.markerIcon,
            opacity: 0.9
          }).addTo(this.stationLayers)  //这里很奇怪 必须在声明就添加到Layergroup中  不然后面无法添加
          // 绑定自动气象站点击事件,弹出嵌套框显示实时气象要素信息
          marker.on('click', () => {
            this.markerform = item
            setTimeout(() => {
              this.markershow = true
            }, 500)
            // 点击平移到站点
            this.map.flyTo([item.latitude, item.longitude])
            this.map.setView([item.latitude, item.longitude], 11)
          })
        })
      })
      // 声明雷达站点图层
      this.radarMarker = L.marker([38.3519444, 114.71194444], {icon: this.radarIcon, opacity: 0.9})
      this.radarStationLayer = L.layerGroup([this.radarMarker])
      this.baseMap = {
        "<span style='font-weight:600'>石家庄区域图层显示</span>": this.stamenLayer
      }
      // 声明外推图层 默认情况下显示当前的图层
      this.rawRadarImageLayer = this.radarImagePrefix + this.currentTimeStamp + ".png"
      this.radarEchoImageLayer = L.layerGroup()
      this.radarEchoImageLayer.addLayer(L.imageOverlay(this.rawRadarImageLayer, this.imageBounds, {opacity: 0.8}))
      // 声明降雨图层
      this.rainImageLayerGroup = L.layerGroup()
      this.rainImageLayerGroup.addLayer(L.imageOverlay(this.rainImagePrefix + this.currentTimeStamp + ".png", this.imageBounds, {opacity: 0.8}))
      this.overlayMap = {
        "自动气象站点图层": this.stationLayers,
        "雷达气象站点图层": this.radarStationLayer,
        "雷达回波外推图层": this.radarEchoImageLayer,
        "降雨估计图层": this.rainImageLayerGroup
      }
      this.map = L.map('map', {
        center: [38.042007, 114.514976],
        zoom: 10, //默认层级
        zoomControl: true,
        attributionControl: true,  //显示右下角注释
        maxZoom: 17,
        minZoom: 10,
        maxBounds: this.layerBounds,  //控制地图边界值显示
        layers: [this.stamenLayer, this.radarEchoImageLayer],  //图层信息
      })
      // 添加laterControl  layercontrol能够更加快速地控制图层显示
      L.control.layers(this.baseMap, this.overlayMap).addTo(this.map)
      // 切换图层的同时显示提示信息
      this.map.on('overlayadd', (e) => {
        this.$message.success("显示" + e.name)
      })
      this.map.on("overlayremove", (e) => {
        this.$message.success("关闭" + e.name)
      })
      // 绑定地图点击事件
      this.map.on('click', (e) => {
        this.$notify({
          title: '事件提醒',
          message: '经纬度坐标为(' + e.latlng.lng.toFixed(2) + "°E" + e.latlng.lat.toFixed(2) + "°N)",
          type: 'success',
          duration: 1000,
        })
      })
    }
    ,
    showImageLayer(imageUrl, index) {
      const imagePath = this.radarImagePrefix + imageUrl + ".png";
      const layer = L.imageOverlay(imagePath, this.imageBounds, {opacity: 0.8})
      this.radarEchoImageLayer.clearLayers()
      this.radarEchoImageLayer.addLayer(layer)
      const rainImagePath = this.rainImagePrefix + imageUrl + ".png";
      const rainLayer = L.imageOverlay(rainImagePath, this.imageBounds, {opacity: 0.8})
      this.rainImageLayerGroup.clearLayers()
      this.rainImageLayerGroup.addLayer(rainLayer)
      this.currentImageIndex = index;
      this.currentTimeStamp = imageUrl;

    }
    ,
    // 时间格式化
    formatTime(imagePath) {
      // 第一个时间戳是不携带"/"和".png"的
      const date = moment(imagePath, 'YYYYMMDDHHmm')
      return date.format('YYYY-MM-DD HH:mm')
    }
    ,

  },
  // 销毁定时器
  beforeDestroy() {
    clearInterval(this.StationInfointerVal)
  },


}
</script>

<style scoped>
.main_map {
  height: 100% !important;
  width: 100%;
}

.window {
  transition: transform 0.3s, background-color 0.3s;
  opacity: 0.8;
  width: 10px;
  text-align: center;
}

.window:hover {
  transform: scale(1.4);
  background-color: rgba(64, 158, 255, 1);
}

.activeButton {
  transform: scale(1.4);
  background-color: #409EFF;
  transition: transform 0.3s, background-color 0.3s;
  opacity: 0.8;
  width: 10px;
  text-align: center;
}
</style>